//
//  LabelEditViewController.m
//  HengHuaSupervision
//
//  Created by wanglong8889@126.com on 14-3-21.
//  Copyright (c) 2014年 XD-XY. All rights reserved.
//

#import "LabelEditViewController.h"
#import "XDTools.h"
#import "XDHeader.h"
#import "SupervisionTagsCell.h"
#import "SaomiaoViewController.h"
#import "TagsEditItem.h"
#import "MainViewController.h"
#import "DetailsViewController.h"

@interface LabelEditViewController ()

@end

@implementation LabelEditViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [self calculateRemindBtnFrame:[XDTools sharedXDTools].waitCumitCount];
    [self calculateRemindBtnFrame:[[NSUserDefaults standardUserDefaults] valueForKey:@"waitCunitCount"]];
    [self initTagDatas];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.tagsArray = [[NSMutableArray alloc] init];
    self.view.frame = CGRectMake(75, 0, self.contentView.frame.size.width-75, self.contentView.frame.size.height);
    self.contentView.frame = CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height);
    dataArrary = [NSMutableArray arrayWithArray:self.sumit_info_array];
    
    [self initLabelEditViews];
}

-(void)initLabelEditViews
{
    //顶部条
    UIImageView * headView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,self.contentView.frame.size.width,mLabelEdit_Head_Img.size.height)];
    headView.image = mLabelEdit_Head_Img;
    headView.userInteractionEnabled =YES;
    [self.contentView addSubview:headView];
    
    //“标签管理”字段
    self.tagCountLabel = [UILabel initLabel:CGRectMake(21, 0, 100, mLabelEdit_Head_Img.size.height) textFont:mHomepage_text_Font textColor:mLabelEdit_Title_Color textAlignment:NSTextAlignmentLeft];
    _tagCountLabel.text = @"标签管理";
    [headView addSubview:_tagCountLabel];
    
    //添加按钮
    UIImage * image = mLabelEdit_Add_Select_Img;
    CGRect rect = CGRectMake(self.contentView.frame.size.width-image.size.width-20, (headView.frame.size.height-image.size.height)/2.0f, image.size.width, image.size.height);
    addTagBtn = [UIButton initButton:rect btnNorImage:mLabelEdit_Add_Normal_Img btnPressBtn:mLabelEdit_Add_Select_Img btnTitle:nil titleColor:nil titleFont:nil];
    [addTagBtn addTarget: self action:@selector(addAssertTags) forControlEvents:UIControlEventTouchDown];
    [headView addSubview:addTagBtn];
    
    
    //列表头
    headTableView = [[UITableView alloc] initWithFrame:CGRectMake(10,height_y(headView)+20, self.contentView.frame.size.width-10-8,mHomepage_head_Height) style:UITableViewStylePlain];
    headTableView.delegate =self;
    headTableView.dataSource = self;
    headTableView.userInteractionEnabled =NO;
    headTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    headTableView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:headTableView];
    
    //列表
    self.tagsTableView = [[UITableView alloc] initWithFrame:CGRectMake(10,height_y(headTableView), self.contentView.frame.size.width-10-8, self.contentView.frame.size.height-(height_y(headTableView))) style:UITableViewStylePlain];
    _tagsTableView.delegate = self;
    _tagsTableView.dataSource = self;
    _tagsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tagsTableView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:_tagsTableView];
                                                                       
}

-(void)initTagDatas
{
    [_tagsArray removeAllObjects];
    FMDatabase * db = [XDTools getDb];
    if (![db open]){
        DDLOG(@"数据库打开失败");
        return;
        
    }
    FMResultSet * rs = [db executeQuery:@"SELECT * FROM T_TRACE_ASSERTS_TAG WHERE assert_id = ?",_assertId];
    while ([rs next]) {
        TagsEditItem * item = [[TagsEditItem alloc] init];
        item.record_id = [rs objectForColumnName:@"id"];
        item.tag_code = [rs objectForColumnName:@"tag_code"];
        item.part = [rs objectForColumnName:@"part"];
        item.create_time = [rs objectForColumnName:@"create_time"];
        item.scan_devicename = [UserInfo sharedUserInfo].scan_devicename;
        
        [_tagsArray addObject:item];
    }
    [db close];
    
    
    if ([_tagsArray count]==0){
        return;
    }
    
    for (int i =0;i < [_tagsArray count];i++){
        TagsEditItem * item = [_tagsArray objectAtIndex:i];
        NSString * last_time = @"0"; //贴标签时，最后一次贴标签的时间
        NSString * last_location;  //最后一次扫描的扫描地点
        NSString * last_location_gps; //最后一次扫描的坐标
        NSString * last_divicename; //最后一次扫描的终端名
        FMDatabase * db2 = [XDTools getDb];
        if (![db2 open]){
            DDLOG(@"数据库打开失败");
            return;
        }
        FMResultSet * rs2 = [db2 executeQuery:@"SELECT * FROM T_TRACE_SCAN_LOG WHERE assert_id = ? and tag_code =?",_assertId,item.tag_code];
        while ([rs2 next]) {
            NSString * status = [rs2 objectForColumnName:@"status"];
            if ([status isEqualToString:@"监造"]){
                NSString * scan_time = [rs2 objectForColumnName:@"scan_time"];
                if ([last_time compare:scan_time] == NSOrderedAscending){
                    last_time = [NSString stringWithFormat:@"%@",scan_time];
                    last_location = [rs2 objectForColumnName:@"scan_location"];
                    last_location_gps = [rs2 objectForColumnName:@"scan_location_gps"];
                    last_divicename = [rs2 objectForColumnName:@"scan_devicename"];
                }
            }
        }
        
        item.scan_time = last_time;
        item.scan_location_gps = last_location_gps;
        item.scan_location = last_location;
        item.scan_devicename = last_divicename;
        item.canEdit =NO;
        [db close];
    }
    
    //判断是否能编辑
    for (int i = 0;i <[_tagsArray count];i++){
        TagsEditItem * item = [_tagsArray objectAtIndex:i];
        FMDatabase * db = [XDTools getDb];
        if (![db open]){
            DDLOG(@"判断是否能删除-->打开数据库失败");
            return;
        }
        FMResultSet * rs = [db executeQuery:@"SELECT * FROM T_TRACE_SUMIT WHERE tag_code = ?",item.tag_code];
        if ([rs next]){
            item.canEdit =YES;
        }else{
            item.canEdit = NO;
        }
        [db close];
    }
    
    //逆序下，如此可以保证可编辑的放在上面
    NSArray * tarray = [NSArray arrayWithArray:_tagsArray];
    [_tagsArray removeAllObjects];
    for (int i =[tarray count]-1; i>=0; i--) {
        [_tagsArray addObject:[tarray objectAtIndex:i]];
    }
    
    
    _tagCountLabel.text =[NSString stringWithFormat:@"标签管理(%d)",[_tagsArray count]];
    [_tagsTableView reloadData];
}

#pragma mark ===================UITableView Delegate======================
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == headTableView){
        return mHomepage_head_Height;
    }else{
        return mHomepage_Cell_Height;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableView == headTableView){
        return 1;
    }else{
        return [_tagsArray count];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView == headTableView){
        static NSString * cellName = @"cell";
        SupervisionTagsCell * cell =[tableView  dequeueReusableCellWithIdentifier:cellName];
        if (cell == nil){
            cell = [[SupervisionTagsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
        }
        cell.diselectBg.image = [XDTools stretchableImag:mHomepage_Head_bg_Img];
        [cell isHarderTableViewCell];
        
        cell.tagIdLabel.text = [self.label_edit_array objectAtIndex:0];
        cell.partLabel.text = [self.label_edit_array objectAtIndex:1];
        cell.DeviceLabel.text = [self.label_edit_array objectAtIndex:2];
        cell.locationLabel.text = [self.label_edit_array objectAtIndex:3];
        cell.createTimeLabel.text = [self.label_edit_array objectAtIndex:4];
        
        return cell;
        
    }else{
        static NSString * cellName = @"cell";
        SupervisionTagsCell * cell =[tableView  dequeueReusableCellWithIdentifier:cellName];
        if (cell == nil){
            cell = [[SupervisionTagsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        if ([_tagsArray count]==0){
            return nil;
        }
        
        if (indexPath.row%2){
            cell.diselectBg.image = [XDTools stretchableImag:mHomepage_Cell_Even_Img];
        }else{
            cell.diselectBg.image = [XDTools stretchableImag:mHomepage_Cell_Odd_Img];
        }
        TagsEditItem * item = [_tagsArray objectAtIndex:indexPath.row];
        cell.tagIdLabel.text = item.tag_code;
        cell.partLabel.text = item.part;
        cell.DeviceLabel.text = item.scan_devicename;
        if (IS_NOT_EMPTY(item.scan_location)){
            cell.locationLabel.text = item.scan_location;
        }else{
            cell.locationLabel.text = item.scan_location_gps;
        }
        cell.createTimeLabel.text=[[XDTools sharedXDTools] intervalSinceNow:item.create_time];
        
        if (item.canEdit){
            cell.userInteractionEnabled =YES;
            cell.tagIdLabel.textColor = [UIColor blueColor];
            cell.partLabel.textColor = [UIColor blueColor];
            cell.DeviceLabel.textColor =[UIColor blueColor];
            cell.locationLabel.textColor = [UIColor blueColor];
            cell.createTimeLabel.textColor = [UIColor blueColor];
        }else{
            cell.userInteractionEnabled = NO;
            cell.tagIdLabel.textColor = mHomepagelist_Text_Color;
            cell.partLabel.textColor = mHomepagelist_Text_Color;
            cell.DeviceLabel.textColor =mHomepagelist_Text_Color;
            cell.locationLabel.textColor = mHomepagelist_Text_Color;
            cell.createTimeLabel.textColor = mHomepagelist_Text_Color;
        }

        CGRect tagRect = [XDTools xyAutoSizeOfWidget:cell.tagIdLabel andSize:CGSizeMake(312/2.0f, 15) andtextFont:15];
        CGRect locationRect = [XDTools xyAutoSizeOfWidget:cell.locationLabel andSize:CGSizeMake(464/2.0f, 15) andtextFont:15];
        CGRect deviceRect = [XDTools xyAutoSizeOfWidget:cell.DeviceLabel andSize:CGSizeMake(309/2.0f, 15) andtextFont:15];
        
        cell.tagIdLabel.frame = CGRectMake(tagRect.origin.x, tagRect.origin.y, 312/2.0f, mHomepage_Cell_Height);
        cell.locationLabel.frame = CGRectMake(locationRect.origin.x, locationRect.origin.y, 464/2.0f, mHomepage_Cell_Height);
        cell.DeviceLabel.frame = CGRectMake(deviceRect.origin.x, deviceRect.origin.y,309/2.0f, mHomepage_Cell_Height);
        
        return cell;
    }
}


//tableview的删除代理方法
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    return UITableViewCellEditingStyleDelete;
    
}

/*改变删除按钮的title*/

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    return @"删除";
    
}


/*删除用到的函数*/

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    if (editingStyle == UITableViewCellEditingStyleDelete){
//        [dataArrary removeObjectAtIndex:[indexPath row]];  //删除数组里的数据
//        
//        [_tagsTableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];  //删除对应数据的cell
        
        //需要更新本地四个表中的数据（设备信息关联表，扫描记录表，贴标签信息表，待提交数据表）
        //删除待提交数据表中的记录
        
        NSString * assert_tag_id;
//        NSString * supervision_id;
        NSString * scan_id;
        FMDatabase * db = [XDTools getDb];
        if (![db open]){
            DDLOG(@"标签管理-->删除标签-->打开数据库失败");
            return;
        }
        TagsEditItem * item = [_tagsArray objectAtIndex:indexPath.row];
        FMResultSet * rs  =[db executeQuery:@"SELECT * FROM T_TRACE_SUMIT WHERE tag_code = ?",item.tag_code];
        if ([rs next]){
            assert_tag_id = [rs objectForColumnName:@"propertyWithlabel_record_id"];
            scan_id = [rs objectForColumnName:@"scan_record_id"];
            
            [db executeUpdate:@"DELETE FROM T_TRACE_SUMIT WHERE tag_code = ?",item.tag_code];
            [db executeUpdate:@"DELETE FROM T_TRACE_SCAN_LOG WHERE id = ?",scan_id];
            [db executeUpdate:@"DELETE FROM T_TRACE_ASSERTS_TAG WHERE id = ?",assert_tag_id];
        }
        [db close];
        
        [_tagsArray removeObjectAtIndex:[indexPath row]];  //删除数组里的数据
        [_tagsTableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];  //删除对应数据的cell
        [_tagsTableView reloadData];
        
        _tagCountLabel.text =[NSString stringWithFormat:@"标签管理(%d)",[_tagsArray count]];
        
        [[XDTools sharedXDTools].mvc initHomePageDatas:nil];
        int count = [[[NSUserDefaults standardUserDefaults] valueForKey:@"waitCunitCount"] intValue];
        count--;
        if (count<=0){
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"waitCunitCount"];
        }else{
            [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"%d",count] forKey:@"waitCunitCount"];
        }
        [self.dvc calculateRemindBtnFrame:[[NSUserDefaults standardUserDefaults] valueForKey:@"waitCunitCount"]];
        [[XDTools sharedXDTools].ivc getWallDatas];
    }
    
}
#pragma mark ===============UiButton Click=====================
-(void)addAssertTags
{
    SaomiaoViewController *saoVC = [[SaomiaoViewController alloc] init];
    [self.navigationController pushViewController:saoVC animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
